home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: Fastest way to computer log(base2) of x?
- Date: Thu, 25 Jan 1996 13:24:26 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601251224.AA06563@dxmint.cern.ch>
- References: <4e61iu$p6e@villa.fc.net> <4e6p7t$1n72@cymbal.aix.calpoly.edu>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- dstubbs@cymbal.aix.calpoly.edu (Dan Stubbs) writes:
-
- >int left_most_bit (int k) {
- >/*
- > * returns the position of the left most bit in k assuming that
- > * k != 0 and 32 bit ints. The algorithm used is essentially a
- > * binary search.
- > */
- > int posn = 0, width = 16, mask = 0xffff0000;
- >
- > while (width > 1) {
- > if (k & mask) {
- > width /= 2;
- > mask <<= (posn + width);
- > mask >>= posn;
- ^^^^^^^^^^^^^^
- > }
- > else {
- > mask >>= width;
- ^^^^^^^^^^^^^^
- Once again: if the sign bit is set (and it is in this example) the
- result of this operation is IMPLEMENTATION-DEFINED. The sign bit may
- be replicated in the "emptied" positions or they may be set to zero.
- Anybody who managed to read the first 49 pages of K&R2 _should_ know this.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-